//var packageType = {"0":"虚捆包","1":"实捆包"};
var initInsertData;

//采购合同子项号、资源号、捆包类型、捆包号、件数、入库量、炉号、库位、厚、宽、长、货主单位、计量方式、备注。
function getStorageFileSubOptions(){
    var initOptions = {
        idField: 'cid',
        fitColumns: false,
        checkOnSelect: false,
        singleSelect: false,
        fit: true,
        columns: [[{
            idField: 'cid',
            width: 20,
            checkbox: true
        }, {
            field: 'contractSubCode',
            title: '采购合同子项号',
            width: 110
        }, {
            title: '资源号',
            field: 'resourceNumber',
            width: 60
        }, {
            field: 'packageType',
            title: '捆包类型',
            width: 60
        }, {
            title: '<label class="redSharp">*捆包号</label>',
            field: 'packageNumber',
            width: 110,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'storagePage',
            title: '<label class="redSharp">*件数</label>',
            width: 60,
            align:'right',
            editor: {
                type: 'numberbox',
                options: {
                    required: true
                }
            }
        }, {
            title: '<label class="redSharp">*入库量</label>',
            field: 'storageNo',
            width: 80,
            editor: {
                    type: 'numberbox',
                    options: {
                        precision: 6,
                        required: true,
                        validType: 'noEmptyNumber'
                    }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatWeight(value);
            }
        }, {
            field: 'furnaceNo',
            title: '炉号',
            width: 60,
            editor:{
                type:'text'
            }
        }, {
            title: '库位',
            field: 'posation',
            width: 60,
            editor:{
                type:'text'
            }
        }, {
            title: '厚',
            field: 'mdThick',
            width: 60
        } ,{
            title: '宽',
            field: 'mdWidths',
            width: 60
        },{
            title: '长',
            field: 'mdLong',
            width: 60
        },{
            title: '货主单位',
            field: 'cargoUnits',
            width: 80
        },{
            title: '计量方式',
            field: 'meteringMethod',
            width: 60
        },{
            title: '备注',
            field: 'remark',
            width: 80,
            editor:{
                type:'text'
            }
        }]],
        toolbar: [{
            id: "addSub",
            text: '新增子项',
            iconCls: 'icon-add'
        }, '-', {
            id: "deleteSub",
            text: '删除子项',
            iconCls: 'icon-remove'
        }],
        onClickCell: onClickCell,
        onAfterEdit: function (rowIndex, rowData, changes) {
            calculateStorageSub(rowIndex, rowData);
            calculateStorageTop();
        }
    }
    return initOptions;

}

var editCellName;
function onClickCell(index, field) {
    if (endEditing($('#subItem'))) {
        editCellName = field;
        if (checkLineStatus($('#subItem'), index)) {
            $('#subItem').datagrid('selectRow', index)
                .datagrid('editCell', {index: index, field: field});
            var ed = $('#subItem').datagrid('getEditor', {index: index, field: field});
            if (ed && ed.target) {
                $(ed.target).focus();
            }
            editIndex = index;
        }
    }
}

function checkLineStatus(node, index) {
    return true;
}

function calculateStorageTop() {
    var subRows = $('#subItem').datagrid('getRows');
    var storageNo = 0;
    var storagePage = 0;
    $.each(subRows, function (index, value) {
        storageNo = storageNo.add(parseFloat(value.storageNo ? value.storageNo : 0));
        storagePage = storagePage.add(parseFloat(value.storagePage ? value.storagePage : 0));
    });
    $('#storageWeight').numberbox('setValue', storageNo.toFixed(6));
    $('#storagePage').numberbox('setValue', storagePage);
}

function calculateStorageSub(rowIndex, rowData){
    if(editCellName === "packageNumber"){
        var columns = $('#subItem').datagrid("options").columns;
// 得到rows对象
        var rows = $('#subItem').datagrid("getRows"); // 这段代码是// 对某个单元格赋值
        var packageNumber= rows[rowIndex][columns[0][getColumnIndex(columns[0], "packageNumber")].field];
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: getContextPath() + "/storage/doublePackage.html",
            data: {packageNumber: packageNumber},
            before: function () {
                parent.$.messager.progress({
                    title: '提示',
                    text: '数据处理中，请稍后....'
                });
            },
            success: function (data) {
                parent.$.messager.progress('close');
                if (data && isSuccess(data.result)) {
                } else {
                    rows[rowIndex][columns[0][getColumnIndex(columns[0], "packageNumber")].field] = packageNumber+"*";
                    // 刷新该行, 只有刷新了才有效果
                    $('#subItem').datagrid('refreshRow', rowIndex);
                    $.messager.show({
                        title: '提示',
                        msg: "捆包号:" + packageNumber + "在数据库中已存在。已在捆包号后添加*变为。'"+ packageNumber+"*'",
                        timeout: 5000,
                        showType: 'fade'
                    });
                }
            },
            timeout: 1000,
            error: function (result) {
//			internalError();
                parent.$.messager.progress('close');
                templateInternalError(result.responseText);

            }
        });
    }
}

function prepareStorageFileSubmitPostData() {
    endEditing($('#subItem'));
    var payData = {};
    var postData = $('#searchForm-small').serializeJson();
    postData.storageDate = $('#storageDate').datebox("getText");
    postData.flagFinish = $('#flagFinish').prop("checked");
    postData.warehouseCode = $('#warehouseCode').combogrid('grid').datagrid('getSelected').warehouseCode;
    //子项表数据
    var subRows = $('#subItem').datagrid('getRows');
    //数据主体结构
    payData.storage = postData;
    payData.storageSubs = subRows;
    return payData;
}

function prepareStorageFileSubmitRealPostData() {
    var data = prepareStorageFileSubmitPostData();
    data.storage.f_contractSubId = $('#contractSubId').text();
    $.each(data.storageSubs, function (index, value) {
        delete value.cid;
    });
    return data;
}

//供应商代码 签约人不能为空
function validateStorageFileTopSubs(flag) {
    if(flag == undefined){
        var memberRow = $('#warehouseCode').combogrid('grid').datagrid('getSelected');
    }

    if (!(memberRow)) {
        return "仓库代码代码不能为空";
    }
    return "true";
}

function validateBottomSubs(data) {
    if (data.length > 0) {
        var packageArrray = [];
        for(var i=0; i<data.length; i++){
            packageArrray.push(data[i].packageNumber);
        }
        var str = "";
        var flag = isRepeat(packageArrray);

        if(flag!=-1){
            var hang = parseFloat(flag) + 1;
            str += "第 " + hang + " 行" + "捆包号重复" + "<br/>";
        }

        $.each(data, function (index, value) {
            var hangNo = index + 1;
            if (isEmpty(value.packageNumber)) {
                str += "第 " + hangNo + " 行" + "捆包号为非空" + "<br/>";
            }
            if (isEmpty(value.storagePage)||value.storagePage< 0) {
                str += "第 " + hangNo + " 行" + "件数为非空正数" + "<br/>";
            }
            if (isEmpty(value.storageNo)||value.storageNo<0) {
                str += "第 " + hangNo + " 行" + "入库量为非空正数" + "<br/>";
            }
        });


        if (str === "") {
            str = "true";
        }
        return str;
    } else {
        return "必须包含有效子项";
    }
}

function initTopStorageFileForm(){
    var data = getStatusData("/storage/selectStorage.html?contractSubId=" + $('#contractSubId').text());
    loadData(data.storage);
    $("#storageType").val("采购入库");
    $('#flagFinish').attr("checked", 'true');
    $('#storageDate').datebox({
        required: true,
        editable: false
    });
    $('#storageDate').datebox("setValue", myformatter(new Date()));
    $('#contractSubCode').text(data.storage.contractSubCode);
    $('#resourceNumber').text(data.storage.resourceNumber);
    $('#storageNumber').numberbox('setValue', data.storage.storageNumber.toFixed(6));
    $('#storageStatus').text(data.storage.storageStatus);
    initInsertData = data.storage;
}


function insertEmptyRow(){
    $('#contractSubCode').text(initInsertData.contractSubCode);
    $('#resourceNumber').text(initInsertData.resourceNumber);
    var ggArray = ggSplitToArray(initInsertData.cpspecification);
    if (ggArray && ggArray.length < 3) {
        var single = ggArray[0];
        ggArray.push(single);
        ggArray.push(single);
    }
    var row = {
        cid: UUID(),
        contractSubCode: $('#contractSubCode').text(),
        resourceNumber: $('#resourceNumber').text(),
        packageType: "实捆包",//TODO list
        storagePage: "1",
        mdThick: ggArray[0],
        mdWidths: ggArray[1],
        mdLong: ggArray[2],
        meteringMethod: "抄码",
        cargoUnits: initInsertData.f_account

    };
    $('#subItem').datagrid('appendRow', row);
    $('#subItem').datagrid('uncheckAll');
    $('#subItem').datagrid('checkRow', $('#subItem').datagrid('getRows').length - 1);
}

function ggSplitToArray(gg){
    return gg.split('*');
}
function refreshEmpty(){

}

//为$('#subItem') 增加子项
function add() {
    endEditing($('#subItem'));
    var rows = $('#subItem').datagrid('getChecked');
    var copRows =[];
    $.each(rows, function (index, value) {
        copRows.push(JSON.parse(JSON.stringify(value)));
    });
    if (rows.length > 0) {
        $.messager.confirm('Confirm', '目前选中[' + rows.length + ']条记录，将他们复制为新纪录吗？', function (r) {
            if (r) {
                $.each(copRows, function (index, value) {
                    value.cid = UUID();
                    $('#subItem').datagrid('appendRow', value);
                })
                $('#subItem').datagrid('uncheckAll');
                $('#subItem').datagrid('checkRow', $('#subItem').datagrid('getRows').length - 1);
            }else{
                insertEmptyRow();
            }
        });
    } else {
        insertEmptyRow();
    }
}

//删除子项
function del() {
    var rows = $('#subItem').datagrid('getChecked');
    var cunzaiIds = [];
    var ids = [];
    if (rows.length > 0) {
        $.each(rows, function (index, value) {
            if (value.id) {
                cunzaiIds.push(value.id);
            }
            ids.push(value.cid);
        });
        if (cunzaiIds.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目,子项全部删除合同将被撤销？', function (r) {
                if (r) {
                    var postData = {
                        'applicationId': $("#applicationId").text(),
                        'applicationSubIds': cunzaiIds
                    }
                    postAjax("/purchase/deleteOneApplicationSub.html", JSON.stringify(postData),
                        refreshEmpty);
                    calculateStorageTop();
                }
            });
        } else if (ids.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目？', function (r) {
                if (r) {
                    $.each(ids, function (index, value) {
                        $('#subItem').datagrid('deleteRow', $('#subItem').datagrid('getRowIndex', value));
                    });
                    calculateStorageTop();
                }
            });
        } else {
            $.messager.alert('提示', '请选择要删除的记录！', 'error');
        }
    }
}


